package threadPoolDemo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Ajie
 * @date 2019-10-23
 * @function
 *
 * fixedThreadPool 运行的runnable 数量 = blockqueue size + （正在执行的数量）
 */
public class FixThreadPool {
    public static void main(String[] args) {
        ThreadPoolExecutor fixedThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);

        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("start");
                    Thread.sleep(6000);
                    System.out.println("over");
                } catch (InterruptedException e) {
                    System.out.println("interrupt----->");
                    e.printStackTrace();
                }
            }
        });

        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("bb");
            }
        });


        BlockingQueue<Runnable> queue = fixedThreadPool.getQueue();
        System.out.println("queue size "+queue.size());
//        fixedThreadPool.shutdownNow();//中断所有任务，并停止接受新任务， 后续加入到任务抛出RejectedExecutionException

        fixedThreadPool.shutdown();//会把队列的任务执行完毕。后续加入的任务， 抛出RejectedExecutionException

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        fixedThreadPool.isTerminated();
        //如果无法将请求加入队列，则创建新的线程，除非创建此线程超出maximumPoolSize，
        //在这种情况下，任务将被拒绝（抛出RejectedExecutionException）。
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("cc");
            }
        });
    }
}
